/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package lime2.ca.treeplain;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import lime2.LimeConstants;
import lime2.LimeServer;
import lime2.Serializer;

/**
 * 
 * A receiver that accepts the RICH_HELLO message and update cast delay
 * @author Xing Jiankuan
 *
 */
class MeshInfoReceiver extends Thread {
	private MulticastSocket rmsock;
	
	private Mesh mesh = Mesh.getInstance();

	public MeshInfoReceiver(MulticastSocket rmsock) {
		this.rmsock = rmsock;
	}

	public void run() {
		boolean close = false;
		
		boolean joined = false;
		
		// joins the multicast group
		while (!joined) {
			try {
				rmsock.joinGroup(TreePlainCA.maddr);
				joined = true;
			} catch (IOException ioe) {
				try {
					Thread.sleep(LimeConstants.DETECT_PHASE);
				} catch (InterruptedException ie) {
				}
			}
		}
		
		while (!close) {
			try {
				byte[] buffer = new byte[LimeConstants.UDP_BUFFER_SIZE];
				DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
				InetAddress here = LimeServer.getServer().getUnicastAddress();
				int port = LimeServer.getServer().getUnicastPort();
				
				// If the source address is local one, ignore it
				rmsock.receive(datagramPacket);
				if(here.equals(datagramPacket.getAddress()) && port == datagramPacket.getPort())
					continue;
				
//				System.out.println("Receive the MeshInfo message from " 
//						+ datagramPacket.getAddress() + ":" + datagramPacket.getPort());
				Object o = Serializer.deserialize(datagramPacket.getData());
				if (o instanceof MeshInfoMsg) {
					MeshInfoMsg msg = (MeshInfoMsg) o; 
					mesh.updateRecord(msg.src, msg.items);
				}

			} catch (Exception e) {
				close = true;
			}
		}
	}
}